package pkg

import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credential "github.com/aliyun/credentials-go/credentials"
)

type Sms interface { //定义一个接口
	SmsCaptcha()
}
type AliSmsCaptcha struct { //定义一个结构体
	Phone string
	Capt  string
}

func (a AliSmsCaptcha) SmsCaptcha() (string, error) { //结构体实现接口
	sms, err := AliSms(a.Phone, a.Capt) //结构体方法调用发信方式
	if err != nil {
		return "", err
	}
	if *sms.Body.Code != "ok" {
		return *sms.Body.Message, err
	}
	return *sms.Body.Message, nil
}
func CreateClient() (_result *dysmsapi20170525.Client, _err error) {
	// 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378661.html。
	credential, _err := credential.NewCredential(nil)
	if _err != nil {
		return _result, _err
	}

	config := &openapi.Config{
		Credential: credential,
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func AliSms(Phone string, Captcha string) (resp *dysmsapi20170525.SendSmsResponse, _err error) {
	client, _err := CreateClient()
	if _err != nil {
		return resp, _err
	}

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		SignName:      tea.String("阿里云短信测试"),
		TemplateCode:  tea.String("SMS_154950909"),
		PhoneNumbers:  tea.String(Phone),                            //替换原本预设为自己手机号
		TemplateParam: tea.String("{\"code\":\"" + Captcha + "\"}"), //替换原本1234为随机值
	}
	runtime := &util.RuntimeOptions{}
	resp, _err = client.SendSmsWithOptions(sendSmsRequest, runtime)
	return resp, _err
}
